layui.define(['jquery', 'element', 'table', "form", "layer"], function (exports) {
    "use strict";

    let $ = layui.$,
        element = layui.element,
        table = layui.table,
        form = layui.form,
        layer = layui.layer;

    let common = {
        open: function (url, title = "", is_form = true) {
            $.ajax({
                url: url,
                type: "get",
                success: function (data) {
                    if (typeof data == "object") {
                        layer.msg(data.msg, { icon: data.code })
                        return
                    }
                    let config = {
                        type: 1, // page 层类型
                        area: ['95%', '95%'],
                        title: title,
                        shade: 0.6, // 遮罩透明度
                        shadeClose: true, // 点击遮罩区域，关闭弹层
                        maxmin: true, // 允许全屏最小化
                        anim: 0, // 0-6 的动画形式，-1 不开启
                        content: data,
                        success: function (layero, index) {
                            form.render();
                        },
                    }
                    if (is_form) {
                        config.btn = ['提交', '重置']
                        config.btn1 = function (index, layero, that) {
                            let loading = layer.load(0);
                            let data = layero.find("form").serializeArray();
                            $.post(url, data, function (res) {
                                if (res.code == 1) {
                                    layer.msg(res.msg, { icon: res.code });
                                    table.reload(Object.keys(table.cache)[0]);
                                } else {
                                    if (res.data != "") {
                                        common.validate(layero, res.data, res.msg);
                                    } else {
                                        layer.msg(res.msg, { icon: res.code });
                                    }
                                }
                                layer.close(loading);
                            })
                        }
                        config.btn2 = function (index, layero, that) {
                            layero.find("form")[0].reset()
                            return false // 点击该按钮后不关闭弹层
                        }
                    }
                    layer.open(config)
                },
                error: function () {
                    layer.msg("网络出错，请稍后再试~")
                }
            })
        },
        /**
         * 刷新表单
         */
        refreshTable: function (name) {
            table.reload(name);
        },
        /**
         * 表单数据删除
         * @param {string} url 
         * @param {object} data 
         */
        tableRemove: function (url, data, msg = "您确定要操作吗?") {
            layer.confirm(msg, { icon: 0 }, function () {
                $.get(url, data, function (res) {
                    layer.msg(res.msg, { icon: res.code }, function () {
                        if (res.code == 1) {
                            table.reload(Object.keys(table.cache)[0])
                        }
                    })
                })
            });
        },
        /**
         * 弹出相册
         * @param {string} elem 绑定事件的元素
         * @param {string} type 类型
         */
        openFiles: function (elem, type = "img") {
            $("body").delegate(elem, "click", function () {
                let src = $(this).attr("src").split(",");
                let alt = $(this).attr("data-title").split(",");
                if (type == "img") {
                    let arr = [];
                    src.forEach(function (v, k) {
                        arr.push({
                            alt: alt[k],
                            pid: k,
                            src: v
                        })
                    })
                    layer.photos({
                        photos: {
                            "title": "相册",
                            "start": 0,
                            "data": arr
                        }
                    })
                } else {
                    window.location.replace($(this).attr("src"));
                }
            })
        },
        /**
         * 修复表单数据
         * @param {object} inputObject 
         * @returns 
         */
        convertObject: function (inputObject) {
            const resultObject = {};
            for (const key in inputObject) {
                if (key.includes('[')) {
                    const parts = key.split('[');
                    const propName = parts[0].trim();
                    const index = parts[1].replace(']', '').trim();

                    if (!resultObject[propName]) {
                        resultObject[propName] = [];
                    }

                    resultObject[propName][index] = inputObject[key];
                } else {
                    resultObject[key] = inputObject[key];
                }
            }
            return resultObject;
        },
        /**
         * 打开附件
         * @param {*} then 同级标签
         * @param {string} url 路径
         * @param {string} key 字段
         */
        openAssets: function (then, url, key = "url") {
            layer.open({
                type: 2,
                title: '附件',
                area: ['620px', '620px'],
                shade: 0.6, // 遮罩透明度
                shadeClose: true, // 点击遮罩区域，关闭弹层
                maxmin: true, // 允许全屏最小化
                anim: 0, // 0-6 的动画形式，-1 不开启
                content: url,
                btn: ['确定', '关闭'],
                btn1: function (index, layero, that) {
                    let sonLayui = layero.context["layui-layer-iframe" + index].layui;
                    let checkStatus = sonLayui.table.checkStatus(Object.keys(sonLayui.table.cache)[0]);
                    if (checkStatus.data.length) {
                        let data = checkStatus.data.map(v => v[key]);
                        let img = $(then).parent().find("img");
                        let input = $(then).parent().find("input");
                        if (data.length == 1) {
                            img.attr("src", data[0]);
                        }
                        input.val(data.join(","));
                        layer.close(index);
                    } else {
                        layer.msg("请勾选数据")
                    }
                }
            })
        },
        /**
         * 表单校验
         * @param {*} layero 表单
         * @param {string} field 字段
         * @param {string} msg 信息
         * @param {number} icons icon
         */
        validate: function (layero, field, msg = "", icons = 5) {
            let DANGER = 'layui-form-danger'; // 警示样式
            let formInput = layero.find('.layui-form .' + DANGER)
            let elem = layero.find(`.layui-form-item *[name="${field}"]`);
            formInput.removeClass(DANGER); // 清除样式
            layer.msg(msg, { icon: icons, shift: 6 });
            elem.focus()
            elem.addClass(DANGER);
        }
    };

    exports("common", common);
});